﻿using Minio.DataModel;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace ManagementApi.Services
{
    /// <summary>
    /// Excel导出帮助类
    /// </summary>
    public class ExcelExportHelper
    {
        /// <summary>
        /// 将数据源转换成Excel工作簿
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="data">数据源</param>
        /// <param name="sheetName">sheet名</param>
        /// <returns></returns>
        public static IWorkbook ExportToExcel<T>(List<T> data, string sheetName = "sheet1")
        {
            IWorkbook workbook = new XSSFWorkbook();
            ISheet sheet = workbook.CreateSheet(sheetName);

            // 添加表头
            IRow headerRow = sheet.CreateRow(0);
            var properties = typeof(T).GetProperties();
            for (int i = 0; i < properties.Length; i++)
            {
                var property = properties[i];
                headerRow.CreateCell(i).SetCellValue(property.Name);
            }

            // 添加数据行
            for (int i = 0; i < data.Count; i++)
            {
                T item = data[i];
                IRow dataRow = sheet.CreateRow(i + 1);
                for (int j = 0; j < properties.Length; j++)
                {
                    var property = properties[j];
                    var value = property.GetValue(item)?.ToString();
                    dataRow.CreateCell(j).SetCellValue(value);
                }
            }

            return workbook;
        }

        /// <summary>
        /// 将Dictionary数据源转换成Excel工作簿
        /// </summary>
        /// <param name="data"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public static IWorkbook ExportToExcel(List<Dictionary<string, string>> data, string sheetName = "sheet1")
        {

            IWorkbook workbook = new XSSFWorkbook();
            ISheet sheet = workbook.CreateSheet(sheetName);

            // 添加表头
            IRow headerRow = sheet.CreateRow(0);
            if (data.Count == 0) { return workbook; }
            var keys = data[0].Keys.ToList();

            for (int i = 0; i < keys.Count; i++)
            {
                headerRow.CreateCell(i).SetCellValue(keys[i]);
            }

            // 添加数据行
            for (int i = 0; i < data.Count; i++)
            {
                IRow dataRow = sheet.CreateRow(i + 1);
                var values = data[i].Values.ToList();
                for (int j = 0; j < values.Count; j++)
                {
                    dataRow.CreateCell(j).SetCellValue(values[j]);
                }
            }

            return workbook;
        }
    }
}
